package com.sky.service.impl;

import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AddressBookServiceImpl implements AddressBookService {
    @Autowired
    private AddressBookMapper addressBookMapper;

    @Override
    public void add(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBook.setIsDefault(StatusConstant.ENABLE);
        if (addressBookMapper.getBYDefault(addressBook)==null){
        addressBookMapper.insert(addressBook);
        }
        else {
            addressBook.setIsDefault(StatusConstant.DISABLE);
            addressBookMapper.insert(addressBook);
        }
    }

    @Override
    public List<AddressBook> list() {
        AddressBook addressBook = new AddressBook();
        addressBook.setUserId(BaseContext.getCurrentId());
        List<AddressBook> list =addressBookMapper.list(addressBook);
        return list;
    }

    @Override
    public AddressBook getById(Long id) {
        AddressBook addressBook = addressBookMapper.getById(id);
        return addressBook;
    }

    @Override
    public void setDefault(AddressBook addressBook) {
            addressBook.setIsDefault(StatusConstant.ENABLE);
            addressBook.setUserId(BaseContext.getCurrentId());
            AddressBook book = addressBookMapper.getBYDefault(addressBook);
            if (book!=null){
            book.setIsDefault(StatusConstant.DISABLE);
            addressBookMapper.updateDefault(book);
            }
            addressBookMapper.updateDefault(addressBook);
    }

    @Override
    public void delete(Long id) {
        addressBookMapper.delete(id);
    }

    @Override
    public void update(AddressBook addressBook) {
        addressBookMapper.update(addressBook);
    }

    @Override
    public AddressBook getBydefault() {
        AddressBook addressBook = AddressBook.builder()
                .userId(BaseContext.getCurrentId())
                .isDefault(StatusConstant.ENABLE)
                .build();
        addressBook=addressBookMapper.getBYDefault(addressBook);
        return addressBook;
    }
}
